package cn.jdy.dzdd.admin;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import cn.jdy.authority.entity.User;
import cn.jdy.common.ctrl.BaseCtrl;
import cn.jdy.dzdd.entity.DzddWorks;
import cn.jdy.dzdd.service.DzddWorksService;
import cn.jdy.framework.log.BaseLog;
import cn.jdy.framework.util.DateUtil;
import cn.jdy.framework.util.NginxPurgeCacheUtil;
import cn.jdy.platform.entity.ConfValue;


/**
 * @author yym
 * @title 通知通报控制类
 * @date 2016/02/16
 */
@Controller
@RequestMapping("/dzddworks")
public class DzddWorksCtrl extends BaseCtrl {

	@Autowired
	private DzddWorksService worksService;
	//默认列表路径
	private static String viewName = "redirect:/dzddworks/list?s=";

	/**
	 * 初始化
	 * @return
	 */
	@RequestMapping("/list")
	public ModelAndView list(DzddWorks entity, String fromDate, String toDate, @RequestParam(required = false) Character s) {
		ModelAndView mv = new ModelAndView("/operate/worksList.jsp");
		if(s != null)
			switch(s) {
				case '1': mv.addObject("msg", "保存成功！");break;
				case '2': mv.addObject("msg", "更新成功！");break;
				case '3': mv.addObject("msg", "删除成功！");break;
				case '4': mv.addObject("msg", "操作失败！");break;
				default: break;
			}
		mv.addObject("entity", entity);
		mv.addObject("fromDate", fromDate);
		mv.addObject("toDate", toDate);
		return mv;
	}

	/**
	 * 异步查询
	 * @param news
	 * @return
	 */
	@RequestMapping("/queryByPage")
	@ResponseBody
	public Map<String, Object> queryByPage(DzddWorks works, String fromDate, String toDate) {
		Map<String, Object> jsonMap = new HashMap<String, Object>();
		try {
			jsonMap.put("dataList", worksService.queryq(works, fromDate, toDate));
			jsonMap.put("iTotalDisplayRecords", worksService.countq(works, fromDate, toDate));
			jsonMap.put("iTotalRecords", worksService.count());
		} catch(Exception e) {
			BaseLog.e(this.getClass(), "查询异常", e);
		}
		return jsonMap;
	}

	/**
	 * 新增
	 * @return
	 */
	@RequestMapping("/edit")
	public ModelAndView edit() {
		return edit(null);
	}

	/**
	 * 编辑
	 * @param id
	 * @return
	 */
	@RequestMapping("/edit/{id}")
	public ModelAndView edit(@PathVariable Long id) {
		ModelAndView mv = new ModelAndView("/operate/worksDetail.jsp");
//		mv.addObject("data", id==null||id==0 ? id : this.worksService.find(id));
		DzddWorks datanewsNews = new DzddWorks();
		if(id==null || id==0){
		datanewsNews.setFalseCreateTime(DateUtil.getCurrentDate(DateUtil._DEFAULT2));
		datanewsNews.setiSignTime(DateUtil.getCurrentDate(DateUtil._DEFAULT2));
		mv.addObject("data", datanewsNews);
	}else{
		DzddWorks works = this.worksService.find(id);
		//投稿统计师将department置null,现将其复原到页面回显
		String[] nd = works.getAssociations();
		if(nd == null){
			String temp=works.getDepars();
			String[] st=temp.split(",");
			int cnt=st.length;
			String[] nds = new String[cnt-1];
			for(int i=1;i<cnt;i++){
				nds[i-1]=st[i];
			}
			works.setAssociations(nds);;
		}
		mv.addObject("data", works);
	}
		// 获得系统所有签收单位
		List<ConfValue> lists = confService.queryByType(72,null);
		mv.addObject("deptList", lists);
		return mv;
	}

	/**
	 * 保存（更新）新闻
	 * @param news
	 * @return
	 */
	@RequestMapping("/save")
	@ResponseBody
	public Map<String, Object> save(DzddWorks works, Long pid) {
		ModelAndView mv = new ModelAndView();
		//将数组转化成String
		Map<String, Object> jsonMap = new HashMap<String, Object>();
		try {
			if(works.getAuthor()!=null&&works.getAuthor()!=""){
				works.setUsername(works.getAuthor());
			}
			if(works.getId()==null) {
				// 新增通知通报
				User user = getUser();
				works.setUserid(user.getId());
				works.setUsername(user.getUsername());
				if(works.getFalseCreateTime() == null || works.getFalseCreateTime() == ""){
					works.setFalseCreateTime(DateUtil.getCurrentDate(DateUtil._DEFAULT2));
				}
				works.setTitle(works.getTitle().trim());
				this.worksService.save(works);
				mv.setViewName(this.viewName.concat("1"));
				jsonMap.put("statusCode", 100);
			} else {
				//更新修改通知通报
				// 新增通知通报
//				User user = getUser();
//				works.setUserid(user.getId());
//				works.setUsername(user.getUsername());
				if(works.getFalseCreateTime() == null || works.getFalseCreateTime() == ""){
					works.setFalseCreateTime(DateUtil.getCurrentDate(DateUtil._DEFAULT2));
				}
				this.worksService.update(works);
				jsonMap.put("statusCode", 200);
				mv.setViewName(this.viewName.concat("2"));
		    // 清理文章缓存
		    NginxPurgeCacheUtil.purge(2, works.getId());
			}
		} catch(Exception e) {
			mv.setViewName(this.viewName.concat("4"));
			jsonMap.put("statusCode", 400);
			BaseLog.e(getClass(), "保存异常！", e);
		}

		return jsonMap;
	}
	
	/**
	 * 删除新闻
	 * @return
	 */
	@RequestMapping("/del/{id}")
	public ModelAndView del(@PathVariable Long id) {
		ModelAndView mv = new ModelAndView();
		try {
			this.worksService.delete(id);
			mv.setViewName(this.viewName.concat("3"));
			// 清理文章缓存
			NginxPurgeCacheUtil.purge(2, id);
		} catch(Exception e) {
			mv.setViewName(this.viewName.concat("4"));
			BaseLog.e(getClass(), "删除异常！", e);
		}
		return mv;
	}

	/**
	 * 襄阳特警
	 * 签收通知通报：多个用户均需要签收
	 * @param id
	 * @param name 登录用户名 String
	 * @return
	 */
	@RequestMapping("/sign/{id}")
	public ModelAndView signed(@PathVariable Long id, String name) {
		ModelAndView mv = new ModelAndView("/operate/worksList.jsp");
		DzddWorks data = this.worksService.find(id);
		if(data.getTeams() == null){
			data.setTeams(name);
			data.setSignStatus("1");
		} else {
			String[] strs = data.getTeams().split(",");
			int cnt=0,len=strs.length;
			for(int i=0;i<len;i++){
				if(!(strs[i].equals(name))){
					cnt++;
				}
			}
			if(cnt>=len){
				data.setTeams(data.getTeams()+","+name);
				data.setSignStatus(data.getSignStatus()+"1");
			}
		}
		this.worksService.update(data);
		return mv;
	}
	
	/**
	 * 市公安局
	 * 复签：只需要发布者一人签收
	 * @param id
	 * @param name
	 * @return
	 */
	@RequestMapping("/counterSign/{id}")
	public ModelAndView ctsigned(@PathVariable Long id, String name) {
		ModelAndView mv = new ModelAndView("/operate/worksList.jsp");
		DzddWorks data = this.worksService.find(id);
		if(name.equals(data.getUsername())){
			data.setSignStatus("1");
		}
		this.worksService.update(data);
		return mv;
	}
	
	/**
	 * 襄阳市公安局
	 * 签收通知通报：多个用户均需要签收
	 * @param id
	 * @param name 登录用户名 String
	 * @return
	 */
	@RequestMapping("/signed/{id}")
	public ModelAndView signeds(@PathVariable Long id, String name) {
		ModelAndView mv = new ModelAndView("/operate/worksList.jsp");
		DzddWorks data = this.worksService.find(id);
		
		String[] assos = data.getDepars().split(",");
		int lens = assos.length;
		String statuses = data.getSignStatus();
		if(statuses==null){
			for(int iter=0;iter<lens;iter++){
				if(assos[iter]!=null && assos[iter].equals(name)){
					data.setSignStatus(name);//将状态1换成用户名
				}
			}
		}else{
			for(int iter=1;iter<lens;iter++){
				//同一账户重复签收无影响 如果先签收jwbzb,接着签收jw此法出错
//				if(assos[iter]!=null && statuses.indexOf(username)==-1 && assos[iter].equals(username)){
				if(assos[iter]!=null && assos[iter].equals(name)){
					if (name.equals("jw")) {
						if(statuses.indexOf("jwbzb")!=-1){//如果有
							if(statuses.indexOf("jw", statuses.indexOf("jwbzb")) ==-1){//随后没有jw
								data.setSignStatus(statuses+","+name);
							}
						}
					} else{
						if(statuses.indexOf(name)==-1)
							data.setSignStatus(statuses+","+name);
					}
				}
			}
		}
		this.worksService.update(data);
		return mv;
	}
	
	/**
	 * 将当前条news设为
	 * 如果有效status=1，改成无效-status=8
	 * 如果无效-status=8，改成有效status=1
	 * @param news
	 * @param id
	 * @return
	 */
	@RequestMapping("/invNews/{id}")
	public ModelAndView invNews(DzddWorks news,@PathVariable Long id) {
		ModelAndView mv = new ModelAndView("redirect:/works/list");
		try {
			DzddWorks data = this.worksService.find(id);
			if(data.getStatus().equals("1")){
				data.setStatus("8");
			}else if(data.getStatus().equals("8")){
				data.setStatus("1");
			}
			this.worksService.update(data);
		} catch (Exception e) {
			BaseLog.e(this.getClass(), "无效有效状态更改异常", e);
		}
		return mv;
	}
}
//String[] ds=works.getAssociations();
//String deps = "";
//for(int i=0;i<46;i++){
//	if(ds[i]==null || ds[i]=="")ds[i]=";";
//	deps += ","+ds[i];
//}
//works.setDepars(deps);
//works.setAssociations(null);

